package news.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import news.model.News;
import news.model.NewsEs;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;

/**
 * @Author: sfy
 * @Date: 2024/1/13 17:11
 */
@RestController
@RequestMapping("/es")
public class EsController {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @GetMapping("/indexOper")
    public String indexOper() throws IOException {

        //新增索引库
//        CreateIndexRequest createIndexRequest = new CreateIndexRequest("users");
//        restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        //判断索引库是否存在
        GetIndexRequest request = new GetIndexRequest("users");
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
        return "indexOper";
    }

    @GetMapping("/docOper")
    public String docOper() throws IOException {
        News news = new News();
        news.setId(1);
        news.setTitle("走过2023丨总书记的民生之“问”");
        NewsEs newsEs = new NewsEs();
        BeanUtils.copyProperties(news,newsEs);
        IndexRequest indexRequest = new IndexRequest("news").id(newsEs.getId().toString());//将对象转为 json 存进 ES
        indexRequest.source(new ObjectMapper().writeValueAsString(newsEs), XContentType.JSON);
        restHighLevelClient.index(indexRequest,RequestOptions.DEFAULT);
        SearchRequest searchRequest = new SearchRequest("news");
        searchRequest.source().query(QueryBuilders.termQuery("title","2023"));//发送查询请求
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);//接收查询结果
        SearchHits hits = search.getHits();//组装查询结果
        ArrayList<NewsEs> list = new ArrayList<>();//取出结果集
        for (SearchHit searchHit : hits.getHits()){
            String json = searchHit.getSourceAsString();
            NewsEs es = new ObjectMapper().readValue(json, NewsEs.class);
            list.add(es);
        }
        list.forEach(System.out::println);
        return "docOper";
    }
}
